<?php
// table_add.php
// SuperConstructor Table Editor
// Creates a new table in the database
// Copyright 2007, Alex McClung
require_once("../lib/func.autoloader.php");

// If the user is not logged in, redirect them to the login page
$sc = new SuperConstructor();
if(false === $sc->getUser()) { header("Location: {$sc->config->LoginPage}"); exit(); }

// Has POST data been submitted?
if(count($_POST) > 0)
{
	// Load post data
	foreach($_POST as $varname=>$value)
	{
		// Ignore everything that begins with an underscore (because it's used by the system)
		if(substr($varname, 0, 1) == "_")
			continue;
			
		// Look in the $_POST['_required'] array, if _colname is in there, it's required
		// So check to make sure it's not empty
		if(array_search($varname, $_POST['_required']) !== false && $value == "")
			MQ::Push("<strong>$varname</strong> is required.", MQ_ERROR);
		else
		{
			// Capture the variable for ourselves, AND give it to the template
			$$varname = $value;
			$sc->assign($varname, $value);
		}
	}
	
	// Validation:
	// Make sure the table name doesn't start with 'sc_'
	if(substr($tablename, 0, 3) == "sc_")
	{
		MQ::Push("Table names cannot begin with <strong>sc_</strong>.", MQ_ERROR);
	}
	
	// If there are no error messages, we can try and create the table
	if( MQ::NumMessages(MQ_ERROR) == 0 )
	{
		// Create a new table object, fill in simple POST data
		$t          = new SimpleTable();
		$t->name    = $tablename;
		$t->comment = $comments;
		
		// Loop through the columns, add 'em to the table
		for($i=0; $i < $num_columns; $i++)
		{
			// First idiot check: make sure the column has a NAME
			if(strlen($colnames[$i]) == 0)
			{
				MQ::Push("Column $i's name is empty", MQ_ERROR);
				continue;
			}
			
			// Create the column, fill in its data, stick it in the table
			$c                 = new SimpleColumn();
			$c->name           = $colnames[$i];
			$c->type           = $coltypes[$i];
			$c->fieldinfo      = $collengths[$i];
			$c->attributes     = $colattribs[$i];
			$c->null           = $colnulls[$i];
			$c->default        = $coldefaults[$i];
			$c->fulltext       = isset($colfulltexts[$i]);
			$c->auto_increment = isset($colincrements[$i]);
			$c->primary_key    = ($colkeys[$i] == "PRIMARY"); // TODO: Replace this with a constant!
			$c->unique         = ($colkeys[$i] == "UNIQUE" ); // TODO: Replace this with a constant!
			$c->index          = ($colkeys[$i] == "INDEX"  ); // TODO: Replace this with a constant!
			$t->AddColumn($c);
		}
		
		// Are there STILL no messages?
		if( MQ::NumMessages(MQ_ERROR) == 0 )
		{
			// Create the table
			if($t->Create())
			{
				// Tell them how awesome they ar.
				MQ::Push("Successfully created <strong>$tablename</strong>", MQ_OK);
				
				// Clear form data
				$sc->clear_assign( array_keys($_POST) );
			}
			else
			{
				// Tell them how badly they failed.
				MQ::Push("Error creating table.", MQ_ERROR);
				MQ::Push($t->LastError(), MQ_ERROR);
			}
		}
	}
}

// Assign some default values for the form so that it will display at least one row
// TODO: Figure out a better way of doing this
$sc->assign("colnames", array("id"));
$sc->assign("coltypes", array("INT"));
$sc->assign("colattribs", array("UNSIGNED"));
$sc->assign("colincrements", array(true));
$sc->assign("colkeys", array("PRIMARY"));

// Assign template vars
$sc->assign("pageTitle", "Create a Table");
$sc->assign("extraStyles",     array("common/css/te.css") );
$sc->assign("extraScripts",    array("common/js/te.js")   );

// TODO: Define these as constants somewhere (or properties of the Column class?)
$sc->assign("_column_types",   array("BIGINT","BINARY","BLOB","BOOL","CHAR","DATE","DATETIME","DECIMAL","DOUBLE","ENUM","FLOAT","INT","LONGBLOB","LONGTEXT","MEDIUMBLOB","MEDIUMINT","MEDIUMTEXT","SET","SMALLINT","TEXT","TIME","TIMESTAMP","TINYBLOB","TINYINT","TINYTEXT","VARCHAR","VARBINARY","YEAR"));
$sc->assign("_column_attribs", array("","UNSIGNED","UNSIGNED ZEROFILL","ON UPDATE CURRENT_TIMESTAMP") );
$sc->assign("_column_nulls",   array("NOT NULL", "NULL")  );
$sc->assign("_column_keys",    array("", "PRIMARY", "INDEX", "UNIQUE") );

// Display the template
$sc->display("admin/pages/table_editor/add.tpl");
?>